class Task < ActiveRecord::Base
  belongs_to :project
  belongs_to :phase
  belongs_to :activity
  has_and_belongs_to_many :users
  has_many :activity_logs
  has_many :task_status_histories
  has_many :workunits
  
  validates_presence_of :name
  validates_presence_of :activity, :message => "(Phase) can't blank."
  
  acts_as_tree
  
  def is_phase?
    self.parent_id.nil?
  end
  
  def working_time
    Workunit.sum(:amount, :conditions => "task_id = #{self.id}")
  end

  #Deprecated. Task cost is no more calculated from worked hours * worker hourly rate, as worker hourly rate may
  #change in future.
  def cost_by_hours
    cost = 0
    workunits = Workunit.sum(:amount, :group => :user_id, :conditions => "task_id = #{self.id}" )
    workunits.each do |user_id, amount|
      cost += User.find_by_id(user_id).hourly_rate.to_i * amount
    end
    cost
  end
  
  #Finds total working cost for task.
  def total_working_cost
    total_cost = workunits.collect { |a| a.cost.to_i}.sum
    total_cost
  end

  #Finds total working hours for task.
  def total_working_hours
    total_hours = workunits.collect { |a| a.amount.to_i}.sum
    total_hours
  end

  #Finds total working hours spent when task is in revision status.
  def total_working_hours_in_revision
    total_hours = 0
    workunits.each { |workunit|
      total_hours += workunit.amount if workunit.at_status ==
        "In Revision" unless workunit.blank?
    }
    total_hours
  end

  #Finds how much weight this activity has in project.
  def weight_in_fee(project)
    ((project.fee * self.weight) / 100).to_i
  end

end